#include "QiliImageLoader.h"

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QPixmap>
#include <QFile>

Q_GLOBAL_STATIC(QNetworkAccessManager, ImageDownloader);

QiliImageLoader::QiliImageLoader(const QString &url, bool loading, QObject *parent)
    : QObject(parent), mUrl(url)
{
    if (loading) {
        load();
    }
}

void QiliImageLoader::load()
{
    if (mUrl.isEmpty()) {
        emit errorOccurred(BadURL, "Empty URL");
        return;
    }
    if (mUrl.startsWith("http://", Qt::CaseInsensitive)
            || mUrl.startsWith("https://", Qt::CaseInsensitive)) {
        auto *reply = ImageDownloader->get(QNetworkRequest(mUrl));
        QObject::connect(reply, &QNetworkReply::finished, [this, reply]{
            if (reply->error() == QNetworkReply::NoError) {
                onRawData(reply->readAll());
            }
        });

        QObject::connect(reply, &QNetworkReply::errorOccurred, [this, reply](auto error) {
            if (error >= QNetworkReply::ProtocolUnknownError
                && error <= QNetworkReply::ProtocolFailure) {
                emit errorOccurred(BadURL, reply->errorString());
            }
            else {
                emit errorOccurred(DataUnavailable, reply->errorString());
            }
        });
        return;
    }

    QFile file(mUrl);
    if (!file.exists()) {
        emit errorOccurred(BadURL, "File not exists");
        return;
    }
    bool successful = file.open(QFile::ReadOnly);
    if (successful) {
        onRawData(file.readAll());
    }
    else {
        emit errorOccurred(DataUnavailable, "File is unreadable");
    }
    file.close();
}

void QiliImageLoader::setUrl(const QString &url)
{
    mUrl = url;
}

void QiliImageLoader::onRawData(const QByteArray &data)
{
    QPixmap pixmap;
    bool successful = pixmap.loadFromData(data);
    if (successful) {
        emit ready(pixmap);
    }
    else {
        emit errorOccurred(ParseFailed, "Unknown image format");
    }
}
